<template>
  <div class="customer-statement">
    <!-- 筛选区 -->
    <el-form :model="filter" inline class="filter-bar">
      <!-- 日期范围 -->
      <el-form-item label="单据日期">
        <el-date-picker
          v-model="filter.dateRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          :default-value="[new Date('2025-06-01'), new Date('2025-06-26')]"
        />
      </el-form-item>

      <!-- 客户选择（弹窗） -->
      <el-form-item label="客户">
        <el-button type="primary" @click="openDialog('customer')">
          {{
            selectedCustomer.name
              ? `${selectedCustomer.code} ${selectedCustomer.name}`
              : "请选择客户"
          }}
        </el-button>
      </el-form-item>

      <!-- 显示商品明细 -->
      <el-form-item>
        <el-checkbox v-model="filter.showGoodsDetail">显示商品明细</el-checkbox>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="queryData">查询</el-button>
        <el-button type="success" @click="exportData">导出</el-button>
        <el-button type="info" @click="printData">打印表格</el-button>
        <el-button type="info" @click="printStatement">打印</el-button>
      </el-form-item>
    </el-form>

    <!-- ========== 客户选择弹窗 ========== -->
    <el-dialog
      title="选择客户"
      v-model="dialogs.customer.visible"
      width="800px"
    >
      <div class="dialog-header">
        <!-- 类别筛选 -->
        <el-select
          v-model="dialogs.customer.categoryFilter"
          placeholder="类别"
          class="mr-4"
        >
          <el-option
            v-for="cat in customerCategories"
            :key="cat"
            :label="cat"
            :value="cat"
          />
        </el-select>

        <!-- 搜索框 -->
        <el-input
          v-model="dialogs.customer.keyword"
          placeholder="输入编号/名称/联系人/电话查询"
          clearable
          style="width: 240px"
        />

        <!-- 显示禁用客户 -->
        <el-checkbox v-model="dialogs.customer.showDisabled" class="ml-4"
          >显示禁用客户</el-checkbox
        >

        <!-- 查询按钮 -->
        <el-button type="primary" class="ml-4" @click="fetchCustomers"
          >查询</el-button
        >
      </div>

      <el-table
        :data="dialogs.customer.list"
        :row-key="(row) => row.id"
        @selection-change="handleCustomerSelect"
        border
        style="width: 100%; margin-top: 8px"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="category" label="类别" min-width="100" />
        <el-table-column prop="code" label="编号" min-width="120" sortable />
        <el-table-column prop="name" label="名称" min-width="180" sortable />
        <el-table-column prop="contact" label="联系人" min-width="100" />
        <el-table-column prop="phone" label="手机" min-width="140" />
        <el-table-column prop="remark" label="备注" min-width="120" />
      </el-table>

      <el-pagination
        @size-change="(val) => (dialogs.customer.limit = val)"
        @current-change="(val) => (dialogs.customer.page = val)"
        :current-page="dialogs.customer.page"
        :page-sizes="[10, 20, 50]"
        :page-size="dialogs.customer.limit"
        :total="dialogs.customer.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 12px"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.customer.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmCustomerSelection"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- ========== 客户对账单表格 ========== -->
    <div class="statement-header" v-if="selectedCustomer.name">
      <h3>云进销存体验账套</h3>
      <h4>客户对账单</h4>
      <p>客户：{{ selectedCustomer.name }}</p>
      <p>联系人：{{ selectedCustomer.contact }}</p>
      <p>电话：{{ selectedCustomer.phone }}</p>
      <p>地址：{{ selectedCustomer.address }}</p>
      <p>日期：{{ filter.dateRange[0] }} 至 {{ filter.dateRange[1] }}</p>
    </div>

    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px"
      show-summary
      :summary-method="generateSummary"
      :header-cell-style="{ background: '#F8F9FA' }"
    >
      <el-table-column
        prop="billDate"
        label="单据日期"
        min-width="120"
        sortable
      />
      <el-table-column
        prop="billNo"
        label="单据编号"
        min-width="120"
        sortable
      />
      <el-table-column prop="businessType" label="业务类别" min-width="100" />
      <el-table-column
        prop="goodsName"
        label="客户物料名称"
        min-width="180"
        v-if="filter.showGoodsDetail"
      />
      <el-table-column
        prop="salesAmount"
        label="销售金额"
        align="right"
        min-width="120"
      />
      <el-table-column
        prop="discountAmount"
        label="优惠金额"
        align="right"
        min-width="120"
      />
      <el-table-column
        prop="customerFee"
        label="客户承担费用"
        align="right"
        min-width="120"
      />
      <el-table-column
        prop="receivableAmount"
        label="应收金额"
        align="right"
        min-width="120"
      />
      <el-table-column
        prop="actualAmount"
        label="实际收款金额"
        align="right"
        min-width="120"
      />
      <el-table-column
        prop="balance"
        label="应收款余额"
        align="right"
        min-width="120"
        sortable
      />
      <el-table-column prop="remark" label="备注" min-width="120" />
    </el-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";

// ========== 筛选条件 ==========
const filter = reactive({
  dateRange: [new Date("2025-06-01"), new Date("2025-06-26")],
  selectedCustomerId: null, // 选中客户ID
  showGoodsDetail: false, // 显示商品明细
});

// ========== 选中客户回显 ==========
const selectedCustomer = ref({
  name: "",
  code: "",
  contact: "",
  phone: "",
  address: "",
});

// ========== 对话框状态 ==========
const dialogs = reactive({
  customer: {
    visible: false,
    categoryFilter: "", // 类别筛选
    keyword: "", // 搜索关键词
    showDisabled: false, // 显示禁用客户
    list: [], // 客户列表
    page: 1, // 分页页码
    limit: 10, // 分页大小
    total: 0, // 总条数
    selected: [], // 选中的客户（多选）
  },
});

// ========== 基础数据模拟 ==========
// 客户类别（从mock数据中提取）
const customerCategories = computed(() => {
  const cats = new Set();
  mockCustomers.forEach((item) => cats.add(item.category));
  return Array.from(cats);
});

// 模拟客户列表（与界面一致）
const mockCustomers = [
  {
    id: 1,
    category: "华中地区",
    code: "1000000",
    name: "客户1",
    contact: "张",
    phone: "15912341234",
    address: "天津天津市和平区批发市场",
    disabled: false,
  },
  {
    id: 2,
    category: "华北地区",
    code: "1000001",
    name: "客户2",
    contact: "李先生",
    phone: "18300000000",
    address: "北京XX区",
    disabled: false,
  },
  {
    id: 3,
    category: "华北地区",
    code: "1000002",
    name: "客户3",
    contact: "王",
    phone: "18212341234",
    address: "河北XX市",
    disabled: true,
  },
  // 更多客户...
];

// 模拟对账数据（按客户1的期初余额）
const mockStatementData = [
  {
    billDate: "",
    billNo: "期初余额",
    businessType: "",
    goodsName: "",
    salesAmount: 0,
    discountAmount: 0,
    customerFee: 0,
    receivableAmount: 0,
    actualAmount: 0,
    balance: 11502.45,
    remark: "",
  },
  // 可扩展更多交易数据...
];

// ========== 对话框交互逻辑 ==========
/** 打开客户选择弹窗 */
const openDialog = (type) => {
  if (type === "customer") {
    dialogs.customer.visible = true;
    fetchCustomers(); // 初始化加载客户
  }
};

/** 获取客户列表（模拟筛选+分页） */
const fetchCustomers = () => {
  const { categoryFilter, keyword, showDisabled, page, limit } =
    dialogs.customer;

  let filtered = mockCustomers.filter((item) => {
    // 类别筛选
    if (categoryFilter && item.category !== categoryFilter) return false;
    // 搜索匹配
    if (keyword) {
      return (
        item.code.includes(keyword) ||
        item.name.includes(keyword) ||
        item.contact.includes(keyword) ||
        item.phone.includes(keyword)
      );
    }
    return true;
  });

  // 禁用筛选
  if (!showDisabled) {
    filtered = filtered.filter((item) => !item.disabled);
  }

  // 分页处理
  const start = (page - 1) * limit;
  const end = start + limit;
  dialogs.customer.list = filtered.slice(start, end);
  dialogs.customer.total = filtered.length;
};

/** 客户多选事件 */
const handleCustomerSelect = (val) => {
  dialogs.customer.selected = val;
};

/** 确认选择客户（仅支持单选，业务逻辑通常为单选） */
const confirmCustomerSelection = () => {
  if (dialogs.customer.selected.length === 0) {
    ElMessage.warning("请选择客户");
    return;
  }
  // 业务场景通常为单选，取第一个
  const selected = dialogs.customer.selected[0];
  selectedCustomer.value = {
    name: selected.name,
    code: selected.code,
    contact: selected.contact,
    phone: selected.phone,
    address: selected.address,
  };
  filter.selectedCustomerId = selected.id;
  dialogs.customer.visible = false;
  ElMessage.success("客户选择成功！");
};

// ========== 数据查询逻辑 ==========
const tableData = ref([]);

/** 查询对账单数据 */
const queryData = () => {
  if (!filter.selectedCustomerId) {
    ElMessage.warning("请先选择客户！");
    tableData.value = [];
    return;
  }
  // 模拟根据客户ID查询数据（此处直接用mock数据）
  tableData.value = mockStatementData;
};

/** 合计行计算（应收款余额） */
const generateSummary = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计:";
      return;
    }
    if (column.prop === "balance") {
      const total = data.reduce((acc, item) => acc + item.balance, 0);
      sums[index] = total.toFixed(2);
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

/** 导出（模拟） */
const exportData = () => {
  if (!filter.selectedCustomerId) {
    ElMessage.warning("请先选择客户！");
    return;
  }
  ElMessage.info("模拟导出对账单...");
};

/** 打印表格（模拟） */
const printData = () => {
  if (!filter.selectedCustomerId) {
    ElMessage.warning("请先选择客户！");
    return;
  }
  ElMessage.info("模拟打印表格...");
};

/** 打印对账单（模拟） */
const printStatement = () => {
  if (!filter.selectedCustomerId) {
    ElMessage.warning("请先选择客户！");
    return;
  }
  ElMessage.info("模拟打印对账单...");
};

// ========== 初始化 ==========
onMounted(() => {
  // 初始无客户，表格为空
  tableData.value = [];
});
</script>

<style scoped>
.customer-statement {
  padding: 24px;
  background: #fff;
}

.filter-bar {
  margin-bottom: 16px;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dialog-footer {
  text-align: right;
}

.statement-header {
  margin-bottom: 12px;
}

.statement-header h3,
.statement-header h4 {
  margin: 4px 0;
  font-weight: 600;
}

/* 合计行样式 */
.el-table__footer-row td {
  background-color: #fff2cc !important;
  font-weight: 500;
}

/* 表头样式 */
.el-table th {
  text-align: center;
}
</style>